import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/config/lf_type_config.dart';
import 'package:largefriends/entity/json/json_parse_utils.dart';
import 'package:largefriends/entity/entities/lf_bool_entity.dart';
import 'package:largefriends/net/error_handle.dart';
import 'package:largefriends/net/lf_api_url.dart';
import 'package:largefriends/net/lf_dio_util.dart';
import 'package:largefriends/net/lf_image_upload.dart';
import 'package:largefriends/res/strings/lf_strings.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/utils/lf_dialog_utils.dart';
import 'package:largefriends/utils/lf_keyboard.dart';
import 'package:largefriends/widgets/dialog_action_tip.dart';
import 'package:largefriends/widgets/lf_image_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

toFeedback({FeedbackType type = FeedbackType.other}) {
  Get.toNamed(LFRoute.pathFeedback, arguments: {'type': type});
}

class LfFeedbackLogic extends GetxController {
  LfAuthService authService = Get.find();
  RxBool emailFocused = false.obs;
  FocusNode emailFocusNode = FocusNode();
  FocusNode contentFocusNode = FocusNode();
  FocusNode phoneFocusNode = FocusNode();
  TextEditingController contentController = TextEditingController();
  TextEditingController phoneNumberController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  RxInt topic = 0.obs;
  RxString content = "".obs;
  RxString phoneNumber = "".obs;
  RxString email = "".obs;

  late FeedbackType typeEnum;

  RxList<AssetEntity> photos = RxList([]);

  @override
  void onInit() {
    typeEnum = Get.arguments['type'];
    if (typeEnum == FeedbackType.password) {
      topic.value = 2;
    } else if (typeEnum == FeedbackType.password) {
      topic.value = 1;
    } else if (typeEnum == FeedbackType.account) {
      topic.value = 4;
    }

    if (authService.loggedIn()) {
      email.value = authService.currentAccount!.email ?? "";
      emailController.text = email.value;
    }

    emailFocusNode.addListener(() {
      emailFocused.value = emailFocusNode.hasFocus;
    });

    super.onInit();
  }

  bool get enableSendFeedback {
    if (authService.loggedIn()) {
      return topic.value > 0 && content.trim().isNotEmpty;
    }
    return topic.value > 0 && email.value.isEmail && content.isNotEmpty;
  }

  sendFeedback() async {
    closeSoftKeyboard();
    showLoading();
    var attachIds = "";
    if (photos.isNotEmpty) {
      var attaches = await uploadFile(fileList: photos.toList());
      attachIds = attaches.map((e) => e.attachId).whereType<String>().join(",");
    }

    Map<String, dynamic> params = {};
    params
      ..put("email", email.value.trim().toString())
      ..put("subject", topic)
      ..put("subject",
          TypeConfig().getValueByKey(LfConfigTypeEnum.feedback, topic.value))
      ..put("content", content.value.trim())
      ..put("phone", phoneNumber.value.trim())
      ..put("attachId", attachIds);

    LfDio()
        .post<LfBoolEntity>(
      url: apiFeedback,
      params: params,
    )
        .then(
      (value) {
        hideLoading();
        showActionTips(
          tips: strSendFeedbackTip.tr,
          actionButtonTip: strOK.tr,
          action: () {
            Get.back();
          },
          showCancel: false,
          dismissible: false,
        );
      },
      onError: (error) {
        hideLoading();
        if (error is NetError) {
          showSnackBar(error.msg);
        }
      },
    );
  }

  addPhoto() {
    LfImagePicker.pickerImage((p0) {
      photos.clear();
      photos.addAll(p0);
    }, maxCount: 3, selected: photos.toList());
  }

  @override
  void onClose() {
    closeSoftKeyboard();
    contentController.dispose();
    emailController.dispose();
    phoneNumberController.dispose();
    contentFocusNode.dispose();
    emailFocusNode.dispose();
    phoneFocusNode.dispose();
    super.onClose();
  }
}

enum FeedbackType {
  password,
  payment,
  account,
  other,
}
